<?php
/**
 * Created by PhpStorm.
 * User: 毛文科
 * Date: 2019/5/25
 * Time: 16:23
 */
namespace app\admin\controller;
use think\Controller;
use think\Db;
use think\Request;

class Databases extends Controller
{
    public function show_list(){
        return NewBuilder::make('table')
//            ->addTableHeaderAllDel('databases/del')
            ->addTableHeaderAdd('databases/show_add','备份')
            ->addTableColumn('id','text','ID')
            ->addTableColumn('path','text','路径')
            ->addTableColumn('remarks','text','备注')
            ->addTableColumn('create_time','text','创建时间')
            ->addTableColumn('name','button','还原',null,'index/huanyuan')
            ->addTableHeaderAllDel('databases/del')
            ->addTableRightHeader('操作')
            ->addTableRight('del','databases/del','删除')
            ->addTablePage('databases/page')
            ->fetch();
    }

    /**加载数据
     * @param Request $request
     * @return \think\response\Json
     */
    public function page(Request $request){
        $limit = $request->param('limit',10);
        $data = Db::name(session('modular').'_databases')
            ->paginate($limit)->toArray();
        foreach ($data['data'] as $key=>$value){
            $value['name'] = '还原';
            if($value['create_time']){
                $value['create_time'] = date('Y-m-d H:i:s',$value['create_time']);
            }
            $data['data'][$key] = $value;
        }
//        $data['data'] = [];
//        $data['total'] = 0;
        return json_page_response($data);
    }

    /**备份
     * @return mixed
     */
    public function show_add(){
        return NewBuilder::make('form')
            ->addAction('index/beifen')
            ->addTextarea('remarks','备注')
            ->addFormButton('submit','备份')
            ->addFormButton('back','返回')
            ->fetch();
    }

    /**删除备份资料
     * @param Request $request
     * @return \think\response\Json
     */
    public function del(Request $request){
        $id = $request->param('id');
        $data = Db::name(session('modular').'_databases')->where('id','in',$id)->select();
        foreach ($data as $value){
            if(is_file('.'.$value['path'])){
                unlink('.'.$value['path']);
            }
            if(is_file('../application/'.session('modular').'/view'.$value['path'])){
                unlink('../application/'.session('modular').'/view'.$value['path']);
            }
        }
        if( Db::name(session('modular').'_databases')->where('id','in',$id)->delete()){
            return json_my_response('删除成功',200);
        }else{
            return json_my_response('删除失败');
        }
    }
}